<script setup>
import {ref} from "vue";
import 'element-plus/theme-chalk/el-message.css'
import {ElMessage} from "element-plus";
import {gamePriceAddAPI} from "@/api/AdminApi/game.js";

const gamePrice = ref({
  gameId: null,
  originPrice: null,
  currentPrice: null,
  discount: null,
  discountStart: null,
  discountEnd: null
})

const rules = {
  originPrice: [
    { required: true, message: '请输入原始价格', trigger: 'blur' },
    { validator: validatePrice, message: '价格必须为数字或小数', trigger: 'blur' }
  ]
}

// 自定义验证器，验证价格是否为数字或小数
function validatePrice(rule, value, callback) {
  if (!isNaN(value) && parseFloat(value) >= 0) {
    callback(); // 符合条件，验证通过
  } else {
    callback(new Error('价格必须为数字或小数')); // 不符合条件，验证失败
  }
}

const formRef = ref()
// 修改按钮
const submit = async (gameId) => {
  gamePrice.value.gameId = gameId
  const res = await gamePriceAddAPI(gamePrice.value)
  if (res.code === 1) {
    return res.code
  } else {
    ElMessage.error(res.msg)
  }
}

// 校验
const validate = async () => {
  try {
    const isValid = await formRef.value.validate();
    if (isValid) {
      return true
    }
  } catch (error) {
    return false
  }
}

// 父组件调用提交方法
defineExpose({
  submit:submit,
  validate:validate
})
</script>

<template>
  <el-form ref="formRef" :model="gamePrice" :rules="rules" label-width="auto" style="max-width: 1200px">
    <el-form-item label="原始价格" prop="originPrice">
      <el-input v-model="gamePrice.originPrice"></el-input>
    </el-form-item>
  </el-form>
</template>

<style scoped>

</style>
